﻿using System;
using Present.Commands.Async.Actions;

namespace Present.Commands.Fluent
{
    public class DelegateAsyncActionBuilder<TParameter, TResult> : ActionBuilder<TParameter, TResult>
    {
        private Action<Exception> handleError = e => { throw new ApplicationException("Excpetion Occurred", e); };
        private Func<ActionExecution<TParameter>, TResult> doWork = x => default(TResult);
        private Action<TResult> handleSuccess = x => { };
        private Func<TParameter, bool> canExecute = x => true;

        protected override IAsyncAction<TParameter, TResult> GetAction()
        {
            return new DelegateAsyncAction<TParameter, TResult>(doWork, handleError, handleSuccess, canExecute);
        }

        public DelegateAsyncActionBuilder<TParameter, TResult> Do(Func<ActionExecution<TParameter>, TResult> doWorkAction)
        {
            this.doWork = doWorkAction;
            return this;
        }

        public DelegateAsyncActionBuilder<TParameter, TResult> Do(Action<ActionExecution<TParameter>> doWorkAction)
        {
            this.doWork = x =>
            {
                doWorkAction(x);
                return default(TResult);
            };
            return this;
        }

        public DelegateAsyncActionBuilder<TParameter, TResult> CanExecuteWhen(Func<TParameter, bool> canExecuteAction)
        {
            this.canExecute = canExecuteAction;
            return this;
        }

        public DelegateAsyncActionBuilder<TParameter, TResult> OnSuccess(Action<TResult> onSuccessAction)
        {
            this.handleSuccess = onSuccessAction;
            return this;
        }

        public DelegateAsyncActionBuilder<TParameter, TResult> OnError(Action<Exception> errorHandler)
        {
            this.handleError = errorHandler;
            return this;
        }

      
    }
}